package com.example.home_app.base.activity

import android.os.Bundle

import com.android.frame.mvp.CommonBaseActivity
import com.example.home_app.R
import com.example.home_app.databinding.ActivitySetDeviceBinding
import com.example.home_app.util.SPTool
import com.example.home_app.util.State
import com.gyf.immersionbar.ImmersionBar

/**
 * Created by dell on 2021/8/11.
 */
class SetActivity: CommonBaseActivity<ActivitySetDeviceBinding>() {
    override fun handleView(savedInstanceState: Bundle?) {
        intView()
        initData()
    }
    private fun intView(){

        ImmersionBar.with(this).titleBar(binding.toolbar).init()
        ImmersionBar.with(this).titleBar(binding.toolbar).keyboardEnable(true).init()
        setSupportActionBar(binding.toolbar)
        val actionBar = supportActionBar
        actionBar?.setDisplayHomeAsUpEnabled(true)
    }
    override fun initListener() {
        //添加设备
        binding.ButtonBt.setOnClickListener {
            dateYan()
        }
        //toolbar返回按钮监听
        binding.toolbar.setNavigationOnClickListener { finish() }
    }
    private fun initData() {
        State.DeviceIDs = SPTool.getInstance(this)?.getString("DeviceIDs", "735471469")
        State.ApiKey =
            SPTool.getInstance(this)?.getString("Api_Key", "FN8vCnpwAjyjTV2m1y=zpL451i4=").toString()
        if (State.DeviceIDs !== "") {
            binding.EditTextIds.setText(State.DeviceIDs)
        }
        if (State.ApiKey !== "") {
            binding.EditTextKey.setText(State.ApiKey)
        }
        State.OTHER = false
    }

    /**
     * 数据验证
     */
    private var key: String? = null
    private var sbid: String? = null
    private var sbids: String? = null
    private fun dateYan() {
        key = binding.EditTextKey.text.toString()
        sbid = binding.EditTextId.text.toString()
        sbids = binding.EditTextIds.text.toString()
        //截取之后的字符
//        String keySum = key.substring(0,key.indexOf("="));
        if (key !!.length > 12 && key !== "") {
            /*设置key*/
            SPTool.getInstance(this) !!.putString("Api_Key", key)
            binding.ImageViewSrc.setImageResource(R.mipmap.ic_right)

            if (sbids !== "") {
                if (sbids !!.length >= 8) {
                    binding.ImageViewSrc2.setImageResource(R.mipmap.ic_right)
                    SPTool.getInstance(this) !!.putString("DeviceIDs", sbids)
                } else {
                    showToast("ID格式有误")
                    binding.ImageViewSrc2.setImageResource(R.mipmap.ic_cuo)
                }
            } else {
                binding.ImageViewSrc2.setImageResource(R.mipmap.wu)
            }
        } else {
            binding.ImageViewSrc.setImageResource(R.mipmap.ic_cuo)
            showToast("API_KEY格式输入有误")
        }
    }
}